package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.client.pb.ResultPb;
import io.kiki.sba.registry.common.model.client.pb.SyncConfigRequestPb;
import io.kiki.sba.registry.common.model.client.pb.SyncConfigResponsePb;
import io.kiki.sba.registry.core.model.SyncConfigResponse;
import io.kiki.sba.registry.server.clientInterface.converter.pb.SyncConfigRequestConvertor;
import io.kiki.sba.registry.server.clientInterface.converter.pb.SyncConfigResponseConvertor;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executor;


public class SyncConfigPbHandler extends AbstractClientDataRequestHandler<SyncConfigRequestPb> {

    @Autowired
    SyncConfigHandler syncConfigHandler;

    static SyncConfigResponsePb fail() {
        SyncConfigResponsePb.Builder builder = SyncConfigResponsePb.newBuilder();
        return builder.setResult(ResultPb.newBuilder().setSuccess(false).setMessage("Unknown sync config response type").build()).build();
    }

    @Override
    protected Node.NodeType getConnectNodeType() {
        return syncConfigHandler.getConnectNodeType();
    }

    /**
     * Reply object.
     */
    @Override
    public Object doHandle(Channel channel, SyncConfigRequestPb message) {

        Object response = syncConfigHandler.doHandle(channel, SyncConfigRequestConvertor.convert2Java(message));
        if (!(response instanceof SyncConfigResponse)) {
            return fail();
        }

        return SyncConfigResponseConvertor.convert2Pb((SyncConfigResponse) response);
    }


    @Override
    public Class interest() {
        return SyncConfigRequestPb.class;
    }

    @Override
    public Executor getExecutor() {
        return syncConfigHandler.getExecutor();
    }
}
